package com.scu.phototabuser.ui.login.login;

import com.scu.phototabuser.data.Taskable;
import com.scu.phototabuser.data.source.local.Token;
import com.scu.phototabuser.data.source.remote.login.LoginTaskable;
import com.scu.phototabuser.data.source.local.User;
import com.scu.phototabuser.util.PreferenceUtil;

import static com.scu.phototabuser.util.Predictions.checkNotNull;

/**
 * Created by tianfei on 2017/4/9.
 */

public class LoginPresenter implements LoginContract.Presenter {

    private LoginContract.LoginView mLoginView;
    private User mUser;
    private LoginTaskable login;

    public LoginPresenter(LoginContract.LoginView mLoginView) {
        this.mLoginView = checkNotNull(mLoginView);
        mLoginView.setPresenter(this);
        mUser=new User();
    }


    @Override
    public void release() {

        //登录的操作必须是同步的，调用release时一定是后台任务响应了，所以这里不需要释放后台任务
        this.login = null;
        this.mLoginView = null;
    }

    @Override
    public void setProgressBarVisibility(boolean visibility) {
        mLoginView.setProgressBarVisibility(visibility);
    }

    @Override
    public void doLogin(String email, String MD5pass, final LoginContract.LoginCallback callback ) {
        mUser.setEmail(email);
        mUser.setPasswordMD5(MD5pass);

        login=new LoginTaskable(mUser.getEmail(),mUser.getPasswordMD5()) {

            @Override
            public void onFailed(Integer code, String msg) {

                callback.showFailed(code,msg);
            }

            @Override
            public void onSuccess(Object data) {
                callback.showSuccess();

                //保存登录数据
                //待完成
                Token t=getToken();
                PreferenceUtil.saveToken(t.getToken());

//                mLoginView.saveIsNeedLogin(false);
                saveIsNeedLogin(false);
                mLoginView.jumpToHome();

                //// FIXME: 2017/4/27 修改登录推送服务器的位置
//                Connector.getInstance().connect();
//                Connector.getInstance().runTask();
            }
        };

        //fixme 注册任务
        //mTask= TaskRepository.newTask(TaskRepository.Tasks.LOGIN_TASK,login);

        login.start(Taskable.TASK_TYPE.LOGIN);
    }

    @Override
    public void saveIsNeedLogin(boolean needDoLogin) {
        PreferenceUtil.saveLoginState(needDoLogin);
    }

    @Override
    public void doSignUp(String email, String MD5pass, LoginContract.LoginCallback callback) {
        return;
    }
}
